package com.dd.census.controller.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dd.census.entity.base.ReturnDto;
import com.dd.census.entity.file.FileDto;
import com.dd.census.properties.Properties;
import com.dd.census.tools.Utils;

@RequestMapping("/file")
@Controller
public class FileController {
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);

	@Autowired
	private Properties properties;

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public ReturnDto upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {

		try {
			String type =request.getParameter("type");
			// 文件目录
			String systemName = System.getProperty("os.name");
			// 文件目录
			String disk = properties.getLocation();
			if(!StringUtils.isBlank(systemName) && systemName.toLowerCase().contains("linux")){
				disk = properties.getLinuxLocation();
			}
			// 系统时间字符串
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			String dayString = sf.format(new Date());
			// 新文件目录
			String diskNew = disk + dayString + File.separator;
			// 系统时间目录不存在则创建
			File dir = new File(diskNew.replace("\\", "/"));
			if (!dir.exists())
				dir.mkdir();
			// 原始文件名
			String nameOriginal = file.getOriginalFilename();
			// 文件扩展名带.
			String suffix = "";
			String suffix2 = "";
			int position = nameOriginal.lastIndexOf(".");
			if (position != -1) {
				suffix = nameOriginal.substring(position, nameOriginal.length());
				suffix2 = nameOriginal.substring(position +1, nameOriginal.length());
			}
			String name = Utils.getRandom() + suffix;
			if("cards".equals(type)) {
				 // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
		        // 读取原图片信息
		        Image srcImg = ImageIO.read(file.getInputStream());
		        int srcImgWidth = srcImg.getWidth(null);
		        int srcImgHeight = srcImg.getHeight(null);
		        // 加水印
		        BufferedImage bufImg = new BufferedImage(srcImgWidth,
		                srcImgHeight,
		                BufferedImage.TYPE_INT_RGB);
		        //获取 Graphics2D 对象
		        Graphics2D g = bufImg.createGraphics();
		        
		        //设置绘图区域
		        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
		        g.rotate(Math.toRadians(30),(double) bufImg.getWidth() / 2,(double) bufImg.getHeight() / 2);
		        //设置字体
		        Font font = new Font("宋体", Font.PLAIN,srcImgWidth/300*20);
		        // 根据图片的背景设置水印颜色
		        g.setColor(Color.gray);
		        g.setFont(font);
		        
		        int x = srcImgWidth - getWatermarkLength("测试", g) - srcImgWidth / 95;
	            int y = srcImgHeight /2;
		        g.drawString("测试", x, y);
		        g.dispose();
		        
		        ImageIO.write(bufImg, suffix2, new File(diskNew + name));
			}else {
				// 保存文件
				file.transferTo(new File(diskNew + name));
			}
			
			// 上传结果
			return new ReturnDto(new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					String path =(File.separator + dayString + File.separator + name).replace("\\", "/");
					put("path", path);
					put("name", nameOriginal);
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 失败了
		return new ReturnDto("上传失败");
	}

	@RequestMapping(value = "/preview", method = RequestMethod.GET)
	public void preview(@RequestParam(value = "path") String path, HttpServletResponse response) {

		FileInputStream in = null;
		OutputStream out = null;
		try {
			// 获取文件
			FileDto fileDto = new FileDto();
			fileDto.setPath(path);
			// 响应头
			response.setContentType("image/png");
			// 文件
			File file = new File(properties.getLocation() + fileDto.getPath().replace("\\", "/"));
			in = new FileInputStream(file);
			// 输出流
			out = response.getOutputStream();
			byte[] buf = new byte[1024];
			int bufsize = 0;
			while ((bufsize = in.read(buf, 0, buf.length)) != -1) {
				out.write(buf, 0, bufsize);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void download(@RequestParam(value = "path") String path, @RequestParam(value = "name") String name, HttpServletResponse response) {

		FileInputStream in = null;
		OutputStream out = null;
		try {
			// 获取文件
			FileDto fileDto = new FileDto();
			fileDto.setPath(path);
			if (path.indexOf(".") > -1) {
				fileDto.setName(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + Utils.getRandom() + path.substring(path.lastIndexOf("."), path.length()));
			} else {
				fileDto.setName(new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + Utils.getRandom());
			}
			// 响应头
			String myFileName= URLEncoder.encode(name ,"utf-8");
			response.setContentType("application/x-download");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + myFileName);
			// 文件
			File file = new File(properties.getLocation() + fileDto.getPath());
			in = new FileInputStream(file);
			// 输出流
			out = response.getOutputStream();
			byte[] buf = new byte[1024];
			int bufsize = 0;
			while ((bufsize = in.read(buf, 0, buf.length)) != -1) {
				out.write(buf, 0, bufsize);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//下载
	@RequestMapping("/downLoadExcel")
	public ResponseEntity<Resource> downLoad(HttpServletResponse response) throws Exception {
		try {
			ClassPathResource cpr = new ClassPathResource("/template/"+"attendanceDemo.xlsx");
			InputStream is = cpr.getInputStream();
			Workbook workbook = new XSSFWorkbook(is);
			String fileName = "员工考勤模板.xlsx";
			downLoadExcel(fileName, response, workbook);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ResponseEntity<Resource>(HttpStatus.OK);
	}

	public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
			workbook.write(response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	 /**
     * 获取水印文字总长度
     * 
     * @param waterMarkContent
     *            水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }
}
